<template>
  <div class="main">
    <div class="left-sider">
      <div class="sider-children">
        <Menu ref="menu" theme="light" :active-name="activeName" :open-names="openNames" accordion>
          <Submenu name="user">
            <template slot="title">
              <Icon type="ios-analytics"/>
              个人管理
            </template>
            <MenuItem name="info" to="/user/info">个人信息</MenuItem>
          </Submenu>

          <Submenu name="order">
            <template slot="title">
              <Icon type="ios-analytics"/>
              订单管理
            </template>
            <MenuItem name="factory" to="/order/factory">厂商列表</MenuItem>
            <MenuItem name="good" to="/order/good">商品列表</MenuItem>
            <MenuItem name="order-list" to="/order/list">订单列表</MenuItem>
          </Submenu>
          <Submenu name="good" v-show="checkUserType">
            <template slot="title">
              <Icon type="ios-analytics"/>
              商品管理
            </template>
            <MenuItem name="good-list" to="/good/list">商品列表</MenuItem>
            <MenuItem name="apply" to="/good/apply">供货列表</MenuItem>
          </Submenu>
        </Menu>
      </div>
    </div>
    <Layout>
      <Header>
        <div class="avatar">
          <Avatar icon="ios-person"/>
          <Dropdown trigger="click" @on-click="dropClick">
            <a href="javascript:void(0)">
              <span class="username">{{$store.state.user.name}}</span>
              <Icon type="ios-arrow-down" color="white"></Icon>
            </a>
            <DropdownMenu slot="list">
              <DropdownItem name="changePwd">修改密码</DropdownItem>
              <DropdownItem name="logout">注销</DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </div>
      </Header>

      <Content class="content">
        <router-view/>
      </Content>
    </Layout>
    <Modal v-model="changePwdModal">
      <p slot="header">
        <span>修改密码</span>
      </p>
      <Form class="form" ref="changePwdForm" :rules="changePwdRules" :model="changePwdForm">
        <FormItem prop="oldPassword">
          <Input type="password" v-model="changePwdForm.oldPassword" placeholder="请输入旧密码">
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="newPassword">
          <Input type="password" v-model="changePwdForm.newPassword" placeholder="请输入新密码">
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
        <FormItem prop="repeatPassword">
          <Input type="password" v-model="changePwdForm.repeatPassword" placeholder="请再输入新密码">
            <Icon type="ios-lock-outline" slot="prepend"></Icon>
          </Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" :loading="changePwdLoading" @click="changePwd">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  export default {
    name: "Main",
    data() {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (value.length < 6) {
          callback(new Error('密码过于简单'));
        } else {
          callback();
        }
      };
      const validateRepeatPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        } else if (this.changePwdForm.newPassword !== value) {
          callback(new Error('两次密码不一致'));
        } else if (this.changePwdForm.oldPassword === value) {
          callback(new Error('新密码不能与原密码相同'));
        } else {
          callback();
        }
      };
      return {
        // 选中菜单
        activeName: "",
        // 打开菜单
        openNames: [],
        // 修改密码模态框
        changePwdModal: false,
        // 修改密码表单
        changePwdForm: {
          oldPassword: "",
          newPassword: "",
          repeatPassword: "",
        },
        // 修改密码载入
        changePwdLoading: false,
        // 修改密码验证
        changePwdRules: {
          oldPassword: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ],
          newPassword: [
            {validator: validatePass, trigger: 'blur'}
          ],
          repeatPassword: [
            {validator: validateRepeatPass, trigger: 'blur'}
          ]
        }
      }
    },
    watch: {
      openNames() {
        this.$nextTick(() => {
          this.$refs["menu"].updateOpened();
        });
      },
      activeName() {
        this.$refs["menu"].updateActiveName();
      },
      $route() {
        this.changeNav();
      }
    },
    computed: {
      checkUserType() {
        return this.$store.state.user.userType === 2;
      }
    },
    methods: {
      userinfo() {
        this.$requests.get("/user/userinfo").then(res => {
          if (res.data.code === 0) {
            const user = res.data.data;
            this.$store.commit("setUser", user);
          }
        })
      },
      dropClick(name) {
        switch (name) {
          case "changePwd": {
            this.changePwdModal = true;
          }
            break;
          case "logout": {
            this.logout();
          }
            break;
        }
      },
      changePwd() {
        const Base64 = require('js-base64').Base64;
        this.$refs["changePwdForm"].validate((valid) => {
          if (valid) {
            this.changePwdLoading = true;
            const params = {
              oldPwd: Base64.encode(this.changePwdForm.oldPassword),
              pwd: Base64.encode(this.changePwdForm.newPassword)
            };
            this.$requests.post("/user/changePwd", params).then(res => {
              if (res.data.code === 0) {
                this.$Message.success("修改成功");
                this.changePwdModal = false;
                this.$refs["changePwdForm"].resetFields();
              } else {
                this.$Message.error(res.data.msg);
              }
              setTimeout(() => {
                this.changePwdLoading = false;
              }, 500)
            })
          }
        })
      },
      logout() {
        sessionStorage.setItem("token", "");
        this.$Message.success("注销成功");
        this.$router.replace("/login");
      },
      changeNav() {
        this.openNames = [this.$route.meta.parent];
        this.activeName = this.$route.name;
      }
    },
    mounted() {
      this.userinfo();
      this.changeNav();
    }
  }
</script>

<style lang="less" scoped>
  .main {
    height: 100%;
    display: flex;

    .left-sider {
      width: 240px;
      flex: 0 0 240px;

      .sider-children {
        height: 100%;
        margin-right: -18px;

        &:after {
          content: '';
          display: block;
          width: 1px;
          height: 100%;
          background: #dcdee2;
          position: absolute;
          top: 0;
          left: 239px;
          z-index: 1;
        }
      }
    }

    .ivu-layout {
      .ivu-layout-header {
        padding: 0;

        .avatar {
          width: 150px;
          height: 100%;
          float: right;

          .ivu-dropdown {
            line-height: 32px;
            margin-left: 10px;

            .username {
              width: 80px;
              word-break: keep-all;
              white-space: nowrap;
              vertical-align: middle;
              overflow: hidden;
              text-overflow: ellipsis;
              text-align: center;
              color: #fff;
            }
          }
        }
      }

      .content {
        padding: 15px 20px 5px 20px;
      }
    }
  }
</style>
